package cultu.community.dao.jpa;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import cultu.community.dao.CommunityDAO;
import cultu.community.message.Community;
import cultu.community.message.CommunityCriteria;
import cultu.community.message.CommunityScenario;
import cultu.framework.dao.jpa.GenericDAOjpa;

/**
 * The Class CommunityDAOjpa.
 */
public class CommunityDAOjpa extends GenericDAOjpa<Community, CommunityCriteria, CommunityScenario> implements CommunityDAO {

  /** The Constant LOG. */
  private static final Logger LOG = Logger.getLogger(CommunityDAOjpa.class);

  /**
   * @see cultu.framework.dao.BaseDAO#get(java.lang.Object, java.lang.Object)
   */
  public Community get(Community c, CommunityScenario s) 
  {
    Community result = null;

    if(c != null && c.getHjid() != null)
    {
      result = get(c.getHjid());
    }
    else
    {
      result = getByCustomKey(c.getUniverseCode(), c.getKindCode(), c.getFamilyCode(), c.getCategoryCode());
    }

    if(result != null && s != null && Boolean.TRUE.equals(s.getManageProducts()))
    {
      try
      {
        result = (Community) entityManager.createQuery("SELECT c FROM Community c " +
            "LEFT JOIN FETCH c.products " +
            "WHERE c.hjid=:hjid")
            .setParameter("hjid", result.getHjid())
            .getSingleResult();
      }
      catch(NoResultException nre)
      {
        LOG.info(nre.getMessage(), nre);
      }
    }

    return result;
  }


  /**
   * Gets the by custom key.
   *
   * @param universe the universe
   * @param kind the kind
   * @param family the family
   * @param category the category
   * @return the by custom key
   */
  private Community getByCustomKey(String universe, String kind, String family, String category)
  {
    Community result = null;

    if(universe != null && !"".equals(universe))
    {
      try
      {

        Query q = entityManager.createQuery("SELECT com FROM Community com " +
            "WHERE com.universeCode " + getStringParam(universe, ":universe") +
            " AND com.kindCode " + getStringParam(kind, ":kind") +
            " AND com.familyCode " + getStringParam(family, ":family") +
            " AND com.categoryCode " + getStringParam(category, ":category"));

        if(universe != null && !"".equals(universe))
        {
          q.setParameter("universe", universe);
        }
        if(kind != null && !"".equals(kind))
        {
          q.setParameter("kind", kind);
        }
        if(family != null && !"".equals(family))
        {
          q.setParameter("family", family);
        }
        if(category != null && !"".equals(category))
        {
          q.setParameter("category", category);
        }

        result = (Community) q.getSingleResult();
      }
      catch(NoResultException nre)
      {
        LOG.info(nre.getMessage(), nre);
      }
    }

    return result;
  }

  /**
   * @see cultu.framework.dao.jpa.GenericDAOjpa#update(cultu.core.message.BaseEntity)
   */
  @Override
  public Community update(Community c) {
    if(validateEntity(c) && c.getHjid() == null)
    {

      try
      {
        Query q = entityManager.createQuery("SELECT com.hjid FROM Community com " +
            "WHERE com.universeCode " + getStringParam(c.getUniverseCode(), ":universe") +
            " AND com.kindCode " + getStringParam(c.getKindCode(), ":kind") +
            " AND com.familyCode " + getStringParam(c.getFamilyCode(), ":family") +
            " AND com.categoryCode " + getStringParam(c.getCategoryCode(), ":category"));

        if(c.getUniverseCode() != null && !"".equals(c.getUniverseCode()))
        {
          q.setParameter("universe", c.getUniverseCode());
        }
        if(c.getKindCode() != null && !"".equals(c.getKindCode()))
        {
          q.setParameter("kind", c.getKindCode());
        }
        if(c.getFamilyCode() != null && !"".equals(c.getFamilyCode()))
        {
          q.setParameter("family", c.getFamilyCode());
        }
        if(c.getCategoryCode() != null && !"".equals(c.getCategoryCode()))
        {
          q.setParameter("category", c.getCategoryCode());
        }

        Long id= (Long) q.getSingleResult();
        
        c.setHjid(id);
      }
      catch(NoResultException nre)
      {
        LOG.info(nre.getMessage(), nre);
      }
    }
    if (null==c){
      return null;
    }
    return entityManager.merge(c);
  }

  /**
   * @see cultu.framework.dao.jpa.GenericDAOjpa#validateEntity(cultu.core.message.BaseEntity)
   */
  @Override
  protected boolean validateEntity(Community pEntity) 
  {
    return pEntity != null && pEntity.getUniverseCode() != null && !"".equals(pEntity.getUniverseCode());
  }

}
